
package com.sun.showcase.biz.testcase.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.showcase.biz.testcase.dao.CaseLibraryDao;
import com.sun.showcase.biz.testcase.service.CaseLibraryService;
import com.sun.showcase.biz.testcase.service.CaseModuleService;
import com.sun.showcase.biz.testcase.service.CaseProjectService;
import com.sun.showcase.client.testcase.domain.CaseLibrary;
import com.sun.showcase.client.testcase.domain.CaseModule;
import com.sun.showcase.client.testcase.domain.CaseProject;
import com.sun.showcase.client.testcase.query.CaseLibraryQuery;
import com.sun.showcase.excel.ReadExcel;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.utils.ArithUtil;
import com.sun.showcase.utils.ExecuteResult;
import com.sun.showcase.utils.LoginContextHolder;
import com.sun.showcase.utils.StringConstant;
@Service("caseLibraryService")
@Transactional
public class CaseLibraryServiceImpl implements CaseLibraryService{
	@Autowired
	private CaseLibraryDao caseLibraryDao;
	@Autowired
	private CaseProjectService caseProjectService;
	@Autowired
	private CaseModuleService caseModuleService;
	
	public void setCaseLibraryDao(CaseLibraryDao dao) {
		this.caseLibraryDao = dao;
	}

	public DataGrid datagrid(CaseLibraryQuery caseLibraryQuery) {
		DataGrid j = new DataGrid();
		Pager<CaseLibrary> pager  = find(caseLibraryQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<CaseLibraryQuery> getQuerysFromEntitys(List<CaseLibrary> caseLibrarys) {
		List<CaseLibraryQuery> caseLibraryQuerys = new ArrayList<CaseLibraryQuery>();
		if (caseLibrarys != null && caseLibrarys.size() > 0) {
			for (CaseLibrary tb : caseLibrarys) {
				CaseLibraryQuery b = new CaseLibraryQuery();
				BeanUtils.copyProperties(tb, b);
				caseLibraryQuerys.add(b);
			}
		}
		return caseLibraryQuerys;
	}

	private Pager<CaseLibrary> find(CaseLibraryQuery caseLibraryQuery) {
		Page<CaseLibrary> page = PageHelper.startPage(caseLibraryQuery.getPage().intValue(), caseLibraryQuery.getRows().intValue());
		List<CaseLibrary> list = caseLibraryDao.findList(caseLibraryQuery);
		Pager<CaseLibrary> pager = new Pager<CaseLibrary>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return  pager;
		
	}
	


	public CaseLibrary add(CaseLibraryQuery caseLibraryQuery) {
		CaseLibrary t = new CaseLibrary();
		this.createOrderIndex(caseLibraryQuery);
		BeanUtils.copyProperties(caseLibraryQuery, t);
		t.setActiveFlag(StringConstant.ONE);
		t.setCreateBy(LoginContextHolder.get().getUserId());
		if(StringUtils.isBlank(t.getCreateByName())){
			t.setCreateByName(LoginContextHolder.get().getUserName());
		}
		t.setCreateDate(new Date());
	    t.setModifiedBy(LoginContextHolder.get().getUserId());
	    t.setModifiedByName(LoginContextHolder.get().getUserName());
	    t.setModifiedDate(new Date());
		caseLibraryDao.save(t);
		caseLibraryQuery.setId(t.getId());
		return t;
		
	}

	private void createOrderIndex(CaseLibraryQuery caseLibraryQuery){
		if(caseLibraryQuery.getOrderIndex() != null){
			return;
		}
		if(caseLibraryQuery.getCurrentCaseId() == null){
			//没有选择插入到哪一个case之前，查询最大的 +1
			CaseLibrary cl = caseLibraryDao.getByMaxOrderIndex();
			if(cl == null){
				caseLibraryQuery.setOrderIndex(1D);
			}else{
				caseLibraryQuery.setOrderIndex(ArithUtil.add(cl.getOrderIndex(),1));
			}
		}else{
			//选择了插入到哪一个case之前
			CaseLibrary cl = this.get(caseLibraryQuery.getCurrentCaseId());
			caseLibraryQuery.setOrderIndex(ArithUtil.add(cl.getOrderIndex(),0.0001));
		}
	}
	public void update(CaseLibraryQuery caseLibraryQuery) {
		CaseLibrary t = caseLibraryDao.getById(caseLibraryQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(caseLibraryQuery, t);
	    	t.setModifiedBy(LoginContextHolder.get().getUserId());
	    	t.setModifiedByName(LoginContextHolder.get().getUserName());
	    	t.setModifiedDate(new Date());
	    	caseLibraryDao.update(t);
		}
	}
	
	/**
	 * 根据条件更新部分字段   新建一个query封装需要更新的字段
	 * searchMap封装更新条件
	 * */
	public void updatePart(CaseLibraryQuery caseLibraryQuery) {
	    caseLibraryDao.updatePart(caseLibraryQuery);
	}

	public void delete(java.lang.Long[] ids) {
		caseLibraryDao.deleteAc(ids);
	}
	
	//逻辑删除 更新状态位
	public void deletePt(java.lang.Long[] ids) {
		caseLibraryDao.deletePt(ids);
	}

	public CaseLibrary get(CaseLibraryQuery caseLibraryQuery) {
		return caseLibraryDao.getById(new Long(caseLibraryQuery.getId()));
	}

	public CaseLibrary get(Long id) {
		return caseLibraryDao.getById(id);
	}

	
	public List<CaseLibraryQuery> listAll(CaseLibraryQuery caseLibraryQuery) {
	    List<CaseLibrary> list = caseLibraryDao.findList(caseLibraryQuery);
		List<CaseLibraryQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	public ExecuteResult<List<CaseLibraryQuery>> checkImportExcelData(InputStream inputStream, String fileName) {
		ExecuteResult<List<CaseLibraryQuery>> res = new ExecuteResult<List<CaseLibraryQuery>>();
		ReadExcel read = new ReadExcel();
		read.setExtension(ReadExcel.getExtension(fileName));
		List<Map<String, String>> data = null;
		try {
			data = read.readExcelStream(inputStream);
		} catch (IOException e) {
		}
		if(data==null || data.size()==0){
			res.addErrorMessage("空模板！");
		}
		List<CaseLibraryQuery> saveList = new ArrayList<CaseLibraryQuery>();
		CaseLibraryQuery excelData;
		CaseLibrary cl = caseLibraryDao.getByMaxOrderIndex();
		Double maxIndex = 1D;
		if(cl != null){
			maxIndex = ArithUtil.add(cl.getOrderIndex(),1);
		}
		maxIndex = maxIndex + data.size();
		int index=2;
		for(Map<String,String> datamap:data){
			if(StringUtils.isEmpty(datamap.get("所属项目ID"))){
				res.addErrorMessage("请录入第"+index+"行【所属项目ID】");
				continue;
			}
			if(StringUtils.isEmpty(datamap.get("所属模块ID"))){
				res.addErrorMessage("请录入第"+index+"行【所属模块ID】");
				continue;
			}
			if(StringUtils.isEmpty(datamap.get("用例标题"))){
				res.addErrorMessage("请录入第"+index+"行【用例标题】");
				continue;
			}
			excelData = new CaseLibraryQuery();
			try {
				excelData.setLibraryCode(Long.valueOf(datamap.get("所属项目ID")));
				CaseProject cp = caseProjectService.get(excelData.getLibraryCode());
				excelData.setLibraryName(cp.getName());
			} catch (Exception e) {
				res.addErrorMessage("请录入正确的【所属项目ID】");
				continue;
			}
			try {
				excelData.setModuleCode(Long.valueOf(datamap.get("所属模块ID")));
				CaseModule cm = caseModuleService.get(excelData.getModuleCode());
				if(cm.getProjectId() != excelData.getLibraryCode()){
					res.addErrorMessage("请录入正确的【所属模块ID】");
					continue;
				}
				excelData.setModuleName(cm.getName());
			} catch (Exception e) {
				res.addErrorMessage("请录入正确的【所属模块ID】");
				continue;
			}
			excelData.setTitle(datamap.get("用例标题"));
			excelData.setPrerequisite(datamap.get("前提条件"));
			excelData.setCaseSteps(datamap.get("用例步骤"));
			excelData.setExpectedResult(datamap.get("预期结果"));
			excelData.setLevel(datamap.get("优先级"));
			excelData.setType(datamap.get("用例类型"));
			excelData.setOrderIndex(maxIndex);
			if(StringUtils.isNotEmpty(datamap.get("创建人"))){
				excelData.setCreateByName(datamap.get("创建人"));
			}
			maxIndex--;
			index++;
			saveList.add(excelData);
		}
		res.setResult(saveList);		
		return res;
	}

	@Override
	public ExecuteResult<CaseLibraryQuery> importExcelData(InputStream inputStream, String fileName) {
		ExecuteResult<CaseLibraryQuery> res = new ExecuteResult<CaseLibraryQuery>();
		
		ExecuteResult<List<CaseLibraryQuery>> checkRes = this.checkImportExcelData(inputStream, fileName);
		
		if(!checkRes.isSuccess()){
			StringBuffer emsg = new StringBuffer();
			for(String errorMsg : checkRes.getErrorMessages()){
				emsg.append(errorMsg);
				emsg.append("\n");
			}
			res.addErrorMessage(emsg.toString());
			return res;
		}
		List<CaseLibraryQuery> datas = checkRes.getResult();
		for(CaseLibraryQuery data : datas){
			this.add(data);
		}
		return res;
	}

	@Override
	public long findPage_count(CaseLibraryQuery caseLibraryQuery) {
		return caseLibraryDao.findPage_count(caseLibraryQuery);
	}
	
	
}
